package com.cgsd.heyu.ui.task;

import android.app.Dialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.android.library.adapter.ViewHelper;
import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.ui.home.fragment.WrapperSendFragment;
import com.cgsd.heyu.ui.task.adapter.MultiOptionAdapter;
import com.cgsd.heyu.ui.task.adapter.OptionAdapter;
import com.cgsd.heyu.ui.task.vo.EditStepTwoVo;
import com.cgsd.heyu.ui.task.vo.OptionVo;
import com.cgsd.heyu.ui.task.vo.StepOneVo;
import com.cgsd.heyu.ui.task.vo.TempStepOneBean;
import com.cgsd.heyu.utils.CommonTools;
import com.cgsd.heyu.utils.RequestParams;
import com.cgsd.heyu.widgets.dialog.WrapperDialog;
import com.cgsd.heyu.widgets.refresh.DensityUtils;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.bean.DateType;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.RequestBody;

/**
 * Author: sky on 2021/3/3 15:56
 * Email: xcode126@126.com
 * Desc: 新建任务-基本信息
 */
public class StepOneFragment extends WrapperSendFragment implements View.OnClickListener {
    private EditText etTitle;
    private EditText etExplain;
    private EditText etApp;
    private TextView tvTaskType;
    private EditText etRequire;
    private EditText etCommitPeriod;
    private EditText etCheckPeriod;
    private TextView tvEndTime;
    private TextView tvRepeatOrder;
    private TextView tvArea;
    private TextView tvSystemLimit;

    private TempStepOneBean tempStepOneBean;
    private StepOneVo stepOneVo;

    public static StepOneFragment newInstance() {
        return new StepOneFragment();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_one_step;
    }

    @Override
    protected void initView() {
        tempStepOneBean = new TempStepOneBean();
        bindViews();
    }

    /**
     * bind views
     */
    private void bindViews() {
        findViewById(R.id.tv_system_limit).setOnClickListener(this);
        findViewById(R.id.tv_task_type).setOnClickListener(this);
        findViewById(R.id.tv_area).setOnClickListener(this);
        findViewById(R.id.tv_end_time).setOnClickListener(this);
        findViewById(R.id.tv_repeat_order).setOnClickListener(this);
        findViewById(R.id.tv_next).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);
        etTitle = findViewById(R.id.et_title);
        etExplain = findViewById(R.id.et_explain);
        etApp = findViewById(R.id.et_app);
        tvTaskType = findViewById(R.id.tv_task_type);
        etRequire = findViewById(R.id.et_require);
        etCommitPeriod = findViewById(R.id.et_commit_period);
        etCheckPeriod = findViewById(R.id.et_check_period);
        tvEndTime = findViewById(R.id.tv_end_time);
        tvRepeatOrder = findViewById(R.id.tv_repeat_order);
        tvArea = findViewById(R.id.tv_area);
        tvSystemLimit = findViewById(R.id.tv_system_limit);
    }

    @Override
    protected void initData() {
        getStepOne();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_task_type:
                if (stepOneVo != null && stepOneVo.catelist != null) {
                    taskType(stepOneVo.catelist);
                } else {
                    showToast(getString(R.string.a_config_error_tip));
                }
                break;
            case R.id.tv_system_limit:
                if (stepOneVo != null && stepOneVo.limit != null) {
                    systemLimit(stepOneVo.limit);
                } else {
                    showToast(getString(R.string.a_config_error_tip));
                }
                break;
            case R.id.tv_area:
                if (stepOneVo != null && stepOneVo.area != null) {
                    selectArea(stepOneVo.area);
                } else {
                    showToast(getString(R.string.a_config_error_tip));
                }
                break;
            case R.id.tv_repeat_order:
                repeatDialog();
                break;
            case R.id.tv_end_time:
                showDatePicker();
                break;
            case R.id.tv_next:
            case R.id.tv_save:
                checkSaveParam();
                break;
        }
    }

    /**
     * 检测输入参数
     */
    private void checkSaveParam() {
        String title = etTitle.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            showToast(getString(R.string.a_input_task_title));
            return;
        }
        String explain = etExplain.getText().toString().trim();
        if (TextUtils.isEmpty(explain)) {
            showToast(getString(R.string.a_input_task_explain));
            return;
        }
        String appName = etApp.getText().toString().trim();
        if (TextUtils.isEmpty(appName)) {
            showToast(getString(R.string.a_input_app_name));
            return;
        }
        String taskType = tvTaskType.getText().toString().trim();
        if (TextUtils.isEmpty(taskType)) {
            showToast(getString(R.string.a_input_task_type));
            return;
        }
        String require = etRequire.getText().toString().trim();
        if (TextUtils.isEmpty(require)) {
            showToast(getString(R.string.a_input_order_require));
            return;
        }
        String commitPeriod = etCommitPeriod.getText().toString().trim();
        if (TextUtils.isEmpty(commitPeriod)) {
            showToast(getString(R.string.a_input_commit_period));
            return;
        }
        String checkPeriod = etCheckPeriod.getText().toString().trim();
        if (TextUtils.isEmpty(checkPeriod)) {
            showToast(getString(R.string.a_input_check_period));
            return;
        }
        String endTime = tvEndTime.getText().toString().trim();
        if (TextUtils.isEmpty(endTime)) {
            showToast(getString(R.string.a_input_end_time));
            return;
        }
        String repeat = tvRepeatOrder.getText().toString().trim();
        if (TextUtils.isEmpty(repeat)) {
            showToast(getString(R.string.a_input_repeat_order));
            return;
        }
        String area = tvArea.getText().toString().trim();
        if (TextUtils.isEmpty(area)) {
            showToast(getString(R.string.a_input_put_area));
            return;
        }
        String systemLimit = tvSystemLimit.getText().toString().trim();
        if (TextUtils.isEmpty(systemLimit)) {
            showToast(getString(R.string.a_input_system_limit));
            return;
        }

        tempStepOneBean.title = title;
        tempStepOneBean.content1 = explain;
        tempStepOneBean.content2 = require;
        tempStepOneBean.apptag = appName;
        tempStepOneBean.finish = Integer.parseInt(commitPeriod);
        tempStepOneBean.check = Integer.parseInt(checkPeriod);

        saveStepOne();
    }

    /**
     * 获取选择窗的基础数据
     */
    private void getStepOne() {
        showLoading();
        RequestBody requestBody = new RequestParams().putUid()
                .putWithoutEmpty("tid", getTid())
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .getStepOne(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<StepOneVo>>() {
                    @Override
                    public void onSuccess(BaseResponse<StepOneVo> baseResponse) {
                        loadSuccess();
                        processEditData(baseResponse);
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        showEmptyView();
                        handleErrorAction(error);
                    }
                });
    }

    /**
     * 处理之前编辑的数据
     *
     * @param baseResponse
     */
    private void processEditData(BaseResponse<StepOneVo> baseResponse) {
        stepOneVo = baseResponse.getBizBody();
        StepOneVo.InfoBean info = stepOneVo.info;
        if (info != null) {
            tempStepOneBean.title = info.title;
            etTitle.setText(info.title);//title

            tempStepOneBean.content1 = info.content1;
            etExplain.setText(info.content1);//任务说明

            tempStepOneBean.apptag = info.tag;
            etApp.setText(info.tag);//app名称

            tempStepOneBean.cateid = info.category_id;
            tvTaskType.setText(info.categorytext);//任务类型

            tempStepOneBean.content2 = info.content2;
            etRequire.setText(info.content2);//接单要求

            tempStepOneBean.finish = info.finish;
            etCommitPeriod.setText(info.finish + "");//提交周期

            tempStepOneBean.check = info.check;
            etCheckPeriod.setText(info.check + "");//审核周期

            tempStepOneBean.endtime = info.endtime;
            tvEndTime.setText(CommonTools.getFormatTime(info.endtime));

            tempStepOneBean.reply = info.reply;
            tvRepeatOrder.setText(info.reply == 1 ? "是" : "否");

            tempStepOneBean.area = info.area;
            tvArea.setText(info.areatext);

            tempStepOneBean.limit = Integer.parseInt(info.limit);
            tvSystemLimit.setText(info.limittext);
        } else {
            //默认显示区域
            if (stepOneVo.area != null && stepOneVo.area.size() > 0) {
                StepOneVo.AreaBean areaBean = stepOneVo.area.get(0);
                tempStepOneBean.area = areaBean.id + "";
                tvArea.setText(areaBean.text);
            }

            //系统限制
            if (stepOneVo.limit != null && stepOneVo.limit.size() > 0) {
                StepOneVo.LimitBean limitBean = stepOneVo.limit.get(0);
                tempStepOneBean.limit = limitBean.id;
                tvSystemLimit.setText(limitBean.text);
            }
            //是否重复接单
            tempStepOneBean.reply = 0;
            tvRepeatOrder.setText("否");
        }
    }

    /**
     * 保存第一步数据
     */
    private void saveStepOne() {
        showSubmitDialog();//return new GsonBuilder().serializeNulls().create().toJson(list);
        RequestBody requestBody = new RequestParams()
                .putWithoutEmpty("tid", getTid())
                .put("taskdata", new GsonBuilder().serializeNulls().create().toJson(tempStepOneBean))
//                .putUid()
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .saveStepOne(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<EditStepTwoVo>>() {
                    @Override
                    public void onSuccess(BaseResponse<EditStepTwoVo> baseResponse) {
                        dismissCommonSubmitDialog();
                        showToast(baseResponse.getResultMsg());
                        skipTwoStep(baseResponse.getBizBody());
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        handleErrorAction(error);
                        dismissCommonSubmitDialog();
                    }
                });
    }

    /**
     * 跳转并处理之前编辑的第二步数据
     *
     * @param twoVo
     */
    private void skipTwoStep(EditStepTwoVo twoVo) {
        if (getActivity() instanceof PublishTaskActivity) {
            PublishTaskActivity activity = (PublishTaskActivity) getActivity();
            activity.setEditStepTwoVo(twoVo);
            activity.setCurrentPage(1, twoVo.id);
        }
    }

    /**
     * 任务类型
     *
     * @param catelist
     */
    private void taskType(List<StepOneVo.CatelistBean> catelist) {
        if (catelist.size() <= 0) {
            showToast(getString(R.string.a_config_error_tip));
            return;
        }
        List<OptionVo> list = new ArrayList<>();
        for (StepOneVo.CatelistBean bean : catelist) {
            list.add(new OptionVo(bean.id, bean.name));
        }

        optionDialog(list, 1);

    }

    /**
     * 处理选择区域
     *
     * @param areaList
     */
    private void selectArea(List<StepOneVo.AreaBean> areaList) {
        if (areaList.size() <= 0) {
            showToast(getString(R.string.a_config_error_tip));
            return;
        }
        List<OptionVo> list = new ArrayList<>();
        for (StepOneVo.AreaBean bean : areaList) {
            list.add(new OptionVo(bean.id, bean.text));
        }
        areaOptionDialog(list);
    }

    /**
     * 系统限制弹窗
     *
     * @param limit
     */
    private void systemLimit(List<StepOneVo.LimitBean> limit) {
        if (limit.size() <= 0) {
            showToast(getString(R.string.a_config_error_tip));
            return;
        }
        List<OptionVo> list = new ArrayList<>();
        for (StepOneVo.LimitBean bean : limit) {
            list.add(new OptionVo(bean.id, bean.text));
        }
        optionDialog(list, 3);
    }

    /**
     * 选择弹窗
     *
     * @param list
     * @param type 1:任务类型；2：投放区域；3：系统限制
     */
    private void optionDialog(List<OptionVo> list, int type) {
        new WrapperDialog(mContext) {
            @Override
            public int getLayoutRes() {
                return R.layout.dialog_system_limit;
            }

            @Override
            protected void setDialogParams(Dialog dialog) {
                setDialogParams(dialog, WindowManager.LayoutParams.MATCH_PARENT,
                        DensityUtils.dp2px(300), Gravity.BOTTOM);
            }

            @Override
            public void help(ViewHelper helper) {
                helper.setOnClickListener(R.id.tv_cancel, view -> dismiss());
                RecyclerView mRecyclerView = helper.getView(R.id.mRecyclerView);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
                OptionAdapter optionAdapter = new OptionAdapter(list);
                mRecyclerView.setAdapter(optionAdapter);
                optionAdapter.setOnItemClickListener((adapter, view, position) -> {
                    OptionVo item = optionAdapter.getItem(position);
                    if (type == 1) {
                        tvTaskType.setText(item.text);
                        tempStepOneBean.cateid = item.id;
                    } else {
                        tvSystemLimit.setText(item.text);
                        tempStepOneBean.limit = item.id;
                    }
                    dismiss();
                });
            }
        }.show();
    }

    /**
     * area option dialog
     *
     * @param list
     */
    private void areaOptionDialog(List<OptionVo> list) {
        new WrapperDialog(mContext) {
            @Override
            public int getLayoutRes() {
                return R.layout.dialog_option_multi;
            }

            @Override
            protected void setDialogParams(Dialog dialog) {
                setDialogParams(dialog, WindowManager.LayoutParams.MATCH_PARENT,
                        DensityUtils.dp2px(450), Gravity.BOTTOM);
            }

            @Override
            public void help(ViewHelper helper) {
                helper.setOnClickListener(R.id.tv_cancel, view -> dismiss());
                RecyclerView mRecyclerView = helper.getView(R.id.mRecyclerView);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
                MultiOptionAdapter optionAdapter = new MultiOptionAdapter(list);
                mRecyclerView.setAdapter(optionAdapter);
                optionAdapter.setOnItemClickListener((adapter, view, position) -> {
                    OptionVo item = optionAdapter.getItem(position);
                    optionAdapter.toggleSelection(item);
                });
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()) {
                            case R.id.tv_confirm:
                                if (optionAdapter.getSelectedCount() == 0) {
                                    showToast("请选择投放区域");
                                    return;
                                }
                                tvArea.setText(optionAdapter.getParamTxt());
                                tempStepOneBean.area = optionAdapter.getParamId();
                                break;
                        }
                        dismiss();
                    }
                }, R.id.tv_cancel, R.id.tv_confirm);
            }
        }.show();
    }

    /**
     * 是否可重复接单弹窗
     */
    private void repeatDialog() {
        new WrapperDialog(mContext) {
            @Override
            public int getLayoutRes() {
                return R.layout.dialog_repeat_order;
            }

            @Override
            protected void setDialogParams(Dialog dialog) {
                setDialogParams(dialog, WindowManager.LayoutParams.MATCH_PARENT,
                        WindowManager.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
            }

            @Override
            public void help(ViewHelper helper) {
                helper.setOnClickListener(view -> {
                    switch (view.getId()) {
                        case R.id.tv_yes:
                            tempStepOneBean.reply = 1;
                            tvRepeatOrder.setText("是");
                            break;
                        case R.id.tv_no:
                            tempStepOneBean.limit = 0;
                            tvRepeatOrder.setText("否");
                            break;
                    }
                    dismiss();
                }, R.id.tv_cancel, R.id.tv_yes, R.id.tv_no);
            }
        }.show();
    }

    /**
     * 展示日期选择
     */
    private void showDatePicker() {
        DatePickDialog dialog = new DatePickDialog(getActivity());
        //设置上下年分限制
        dialog.setYearLimt(5);
        //设置标题
        dialog.setTitle("选择时间");
        //设置类型
        dialog.setType(DateType.TYPE_ALL);
        //设置消息体的显示格式，日期格式
        dialog.setMessageFormat("yyyy-MM-dd HH:mm");
        //设置选择回调
        dialog.setOnChangeLisener(null);
        //设置点击确定按钮回调
        dialog.setOnSureLisener(date -> {
            tvEndTime.setText(CommonTools.dateToStr(date));
            tempStepOneBean.endtime = date.getTime() / 1000;
        });
        dialog.show();
//        new DateTimeSelector(mContext).addHelperAbsCallback((wrapper, dialog, helper)
//                -> helper.setOnClickListener(v -> {
//            switch (v.getId()) {
//                case R.id.tv_confirm:
//                    String date = ((DateTimeSelector) wrapper).getSelectedDate();
//                    tvEndTime.setText(date);
//                    tempStepOneBean.endtime = CommonTools.dateToLong(date) / 1000;
//                    break;
//            }
//            dialog.dismiss();
//        }, R.id.tv_cancel, R.id.tv_confirm)).show();
    }

    /**
     * 获取任务id
     *
     * @return
     */
    private int getTid() {
        if (getActivity() instanceof PublishTaskActivity) {
            PublishTaskActivity activity = (PublishTaskActivity) getActivity();
            return activity.getTid();
        }
        return -1;
    }

    @Override
    public void onRefresh(Object t) {

    }
}
